/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.user;

import com.servengine.struts.AdminServiceAction;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

 /**
	* This struts action class groups user admin actions.
	* @see UserActionForm
	* @see UserActions
	*/
public class UserAdminActions extends com.servengine.struts.ClientAction implements AdminServiceAction
{
	private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog( UserAdminActions.class.getName() );
//	MailRelayLocal mailRelay;

	public void initAction(javax.naming.Context context)
	{
		/*try
	  {
	    mailRelay = (MailRelayLocal)initialcontext.lookup("MailRelay/local");
	  } catch (Exception e)
	  {
	    log.error(e.getMessage(), e);
	    throw new IllegalStateException(e.getMessage());
	  }*/
		log.info(getClass().getName()+" initialized");
	}

	public ActionForward store(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		try
		{
		  UserSessionSBean userSession=getUserSession(request);
		  UserActionForm userForm = (UserActionForm)form;
		  if (userForm.getPortalid()!=null && !userForm.getPortalid().equals(userSession.getPortalid()))//TODO Borrar por que creo que sobra esta comprobación
		    throw new IllegalArgumentException();
			User user = userForm.getId()==null? new User(userSession.getPortal(),userForm.getUserid()):
				usermanager.getUser(userSession.getPortalid(),userForm.getId());
			String password = user.getPassword(); // El siguiente copy properties va a borrarla.
			PropertyUtils.copyProperties(user,userForm);
		  if (userForm.getNewpassword()!=null && userForm.getNewpassword().length()>0)
			{
				if (!userForm.getNewpassword().equals(userForm.getNewpassword2()))
					throw new IllegalArgumentException("error.passwordsMustBeTheSame");
		    user.encodePassword(userForm.getNewpassword());
				userForm.setNewpassword(null);
				userForm.setNewpassword2(null);
			} else
			  user.setPassword(password);//Volvemos a poner la que tenía antes
		  usermanager.persist(user, userForm.getExtraUserdataMap());
			userForm.setId(user.getId());
			if (userForm.getRoleIds()!=null)
				usermanager.setUserRoles(userSession.getPortalid(),user.getId(),userForm.getRoleIds());
		  logManager.log(userSession.getPortalid(),userSession.getUser().getId(),"user","UserAdminActions","store",user.getUserid(),request.getRemoteAddr());
		  return unspecified(mapping,form,request,response);
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
		  saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
	  UserSessionSBean userSession=getUserSession(request);
		UserActionForm edituser = (UserActionForm)form;
		try
		{
			User userdto = edituser.getId()!=null ?
				usermanager.getUser(userSession.getPortalid(),edituser.getId()):
				usermanager.getUser(userSession.getPortalid(),edituser.getUserid());
			if (!userdto.getPortalid().equals(userSession.getPortalid()))
				throw new IllegalArgumentException();
			BeanUtils.copyProperties(edituser,userdto);
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
		  saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	  return mapping.findForward("success");
	}

	public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		try
		{
		  UserSessionSBean userSession=getUserSession(request);
		  UserActionForm edituser = (UserActionForm)form;
			User userdto = edituser.getUserid()==null?new User(userSession.getPortal()):
				new User(userSession.getPortal(),edituser.getUserid());
			BeanUtils.copyProperties(edituser,userdto); // Por si acaso
			 return mapping.findForward("success");
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
		  saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
	
	public ActionForward sendSignupconfirmationrequestmail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		try
		{
		  UserSessionSBean userSession=getUserSession(request);
			User user = usermanager.getUser(userSession.getPortalid(),((UserActionForm)form).getUserid());
			request.setAttribute("user",user);
		  String html = getServletContextUtils().getResourceAsString(userSession.getUser(),request,response,"/user/admin/UserSignupConfirmationRequestMail.jsp");
		  getMailRelay().send(portalmanager.getEmail(userSession.getPortalid()).getAddress(), userSession.getUser().getEmail(), "Signup confirmation", null, html);
			//usermanager.sendSignupconfirmationrequestmail(usermanager.getUser(userSession.getPortalid(),edituser.getId()));
			 return mapping.findForward("success");
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
		  saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

/*	public ActionForward sendPasswordchangerequest(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
	  UserSessionSBean userSession=getUserSession(request);
	  UserActionForm edituser = (UserActionForm)form;
	  try
	  {
		  usermanager.sendPasswordchangerequest(userSession.getPortalid(),edituser.getId());
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
		  saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
		return mapping.findForward("success");
	}*/
}
